<template>
  <div class="home">
    <input
      type="text"
      v-model="inputVal"
      placeholder="请输入你的任务名称，按回车键确认"
      @keydown.enter="add"
    />
    <ul>
      <li v-for="(item,index) in $store.state.list" :key="index">
        <input type="checkbox" v-model="item.isCheck"/> &#x3000; {{item.msg}}
        <button @click="del(index)">删除</button>
      </li>
    </ul>
    <div class="foot">
      <span
        >全选
        <input type="checkbox" v-model="allCheck" @change="check"/>
      </span>
      <span style="margin-left: 20px"> 已选择：{{checkLength}} / 全部：{{$store.state.list.length}} </span>
      <button :style="{width: '100px', display: checkLength?'inline-block':''}" @click="delCheck">删除已选中</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",
  data() {
    return {
      inputVal: "",
      allCheck: false
    };
  },
  computed:{
    checkLength(){
      return this.$store.state.list.filter(item => item.isCheck).length;
    }
  },
  watch:{
    checkLength(){
      // if (this.checkLength == this.$store.state.list.length){
      //   this.allCheck = true
      // } else {
      //   this.allCheck = false
      // }
      if (this.$store.state.list.length == 0){
        this.allCheck = false;
        return
      }
      this.allCheck = this.checkLength == this.$store.state.list.length
    }
  },
  methods:{
    add(){
      if (!this.inputVal){
        alert('内容不能为空')
      } else {
        this.$store.commit('addList',this.inputVal);
        this.inputVal = '';
      }
    },
    check(){ // 全选的事件
      // console.log(this.allCheck);
      this.$store.state.list.forEach(item => {
        item.isCheck = this.allCheck;
      })
    },
    del(i){
      this.$store.commit('delect',i);
    },
    delCheck(){
      this.$store.commit('delectCheck');
    }
  }
};
</script>
<style lang="scss">
.home {
  width: 600px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 100px auto;
  padding: 0 20px;
}
input[type="text"] {
  height: 30px;
  width: 100%;
  margin-top: 20px;
  padding: 0 10px;
  box-sizing: border-box;
}
ul {
  border: 1px solid #ccc;
  margin-top: 30px;
  border-radius: 5px;
  li {
    display: flex;
    height: 40px;
    align-items: center;
    padding: 0 10px;

    &:hover {
      background: #ccc;
      button {
        display: inline-block;
      }
    }
  }
}
button {
  width: 60px;
  padding: 4px 0;
  border: none;
  border-radius: 4px;
  background: red;
  display: none;
  color: #fff;
  cursor: pointer;
  margin-left: auto;
}
.foot {
  display: flex;
  height: 60px;
  align-items: center;
}
</style>
